const fs = require('fs');
const rootPath = require('app-root-path');
const makeDir = require('make-dir');
const jpart = require("../../lib/jpart")
const {host} = require("../../config/config")
const path =require('path');
const { log } = require('console');

// 文件工具类
const sfile = {
	uploadRoot: '/temporary',	// 上传文件根目录
	webRoot: rootPath + '/public',	// web项目路径
	istype:	['png','jpeg','web','gif'],	//允许上传文件类型
	delay:	1000*60*60*3,	// 文件保存时间 
	imageSize: 400,		// 保存图片大小
	quality: 50,		// 图片压缩质量，100表示最好
	// 获取扩展名
	getExtension: function(filename){
		if (filename){
			let p = filename.lastIndexOf('.');
			if (p != -1)
				return filename.substring(p + 1);
		}
	},
	// 自动重命名
	autoFilename: function(source, dir, filename){
		let catalog = this.webRoot + dir + '/';
		// 添加扩展名
		let ext = this.getExtension(source);
		if (!ext)
			ext = "";
		else
			ext = "." + ext;
		
		// 如果存在重名，则添加序号
		let n = 1;
		let rename = filename;
		while (fs.existsSync(catalog + rename + ext)){
			// console.log("文件已存在：" + rename + ext);
			rename = filename + "-" + n;
			n++;
		}
		return rename + ext;
	},
	// 是否可以访问目录
	accessDir: function(dir){
		return dir.substring(0, this.uploadRoot.length) == this.uploadRoot;
	},
	// 判断文件是否为图片
	isImage: function(name){
		const extArray = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
		let ext = this.getExtension(name);
		if (!ext)
			return false;
		return extArray.indexOf(ext) != -1;
	},
	// 创建缩略图
	saveImage: function(dir, name, size){
		if (!dir) return null;
		if (typeof name == 'number'){
			size = name;
			name = '';
		}
		let source;
		if (!name){
			source = dir;
			let p = dir.lastIndexOf('/');
			if (p == -1 || p == 0){
				name = dir;
				dir = '/';
			} else {
				name = dir.substring(p + 1);
				dir = dir.substring(0, p);
			}
		} else {
			source = dir + '/' + name;
		}
		// 检查源文件是否存在
		let pathname = this.webRoot + source;
		if (!fs.existsSync(pathname)){
			return null;
		}
		let img = images(pathname);
		let width = img.width();
		let height = img.height();
		// console.log('width=' + width + ', height=' + height);
	
		// 限制图片大小
		if (!size) size = this.imageSize;
		if (width < height){
			width = Math.round(width*size/height);
			height = size;
		} else {
			width = size;
			height = Math.round(height*size/width)
		}
		// console.log('width=' + width + ', height=' + height);
		img.resize(width);
		let catalog = this.webRoot + this.thumbDir + dir;
		if (!fs.existsSync(catalog)){
			makeDir.sync(catalog);
		}
		img.save(catalog + '/' + name, {quality: this.quality});
		return this.thumbDir + dir + '/' + name;
	},
	// 给文件夹中的所有图片创建缩略图
	build: function(dir, size){
		if (!dir) return 0;
		let catalog = sfile.webRoot + dir;
		// 检查目录是否存在
		if (!fs.existsSync(catalog)){
			return 0;
		}
		// 如果 dir 是文件夹
		let stat = fs.statSync(catalog);
		if (stat.isDirectory){
			let sum = 0;
			for (let fname of fs.readdirSync(catalog)) {
				stat = fs.statSync(catalog + '/' + fname);
				if (stat.isFile() && this.isImage(fname)){
					this.saveImage(dir, fname, size);
					sum++;
				}
			}
			return sum;	
		}
		// 如果 dir 是文件
		if (this.isImage(dir)){
			this.saveImage(dir, size);
			return 1;
		}
		return 0;
	},
	// 延时删除文件
	delayDelete: function(path){
		if (!path) return;
		// 检查源文件是否存在
		if (!fs.existsSync(path)){
			return;
		}
		setTimeout(function(){
			fs.unlinkSync(path);
		}, this.delay);
	}
}

module.exports = {
    //将临时文件保存到指定目录
	// obj对象需要有paths图片路径数组，dir保存文件路径
	save: async (db,obj) => {
		let paths = obj.paths;
		if(!paths instanceof Array)
			return {
				code:1004,
				message: 'paths不是一个数组'
			}
		let urls = [];
		try {
			paths.forEach(path => {
				if(typeof path == 'string'){
					path = path.indexOf('temporary/')?path.split('temporary/')[1]:path;
					
					
					let oldPath = sfile.webRoot + '/temporary/' + path;		
					// let newPath = sfile.webRoot + obj.dir + '/' + jpart.formatDate(new Date(), 'yyyy-MM-dd')		
					let newPath = sfile.webRoot + obj.dir 
					// 判断旧文件是否存在
					if (fs.existsSync(oldPath)){
						// 判断新路径是否存在
						if (!fs.existsSync(newPath)){
							fs.mkdirSync(newPath);
						}
						newPath += '/' + path; 
						// 移动文件
						fs.renameSync(oldPath, newPath);
						
						urls.push( newPath.split('/public')[1]);
					}
				}
			})		
			return urls
			return {code: 1000, data: {
				urls
			}}	
		}catch(e){
			console.log(e);
			return  {code: 1004, message: `上传路径不存在,请确认`};
		}			
	},
}